package com.sino.operation.service.basic;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sino.operation.Exception.exceptionRoot.SinoException;
import com.sino.operation.commons.commonEnum.PasswordNeedUpdateFlag;
import com.sino.operation.commons.commonEnum.TellerState;
import com.sino.operation.commons.commonEnum.TellerWorkState;
import com.sino.operation.commons.response.CenterResponseEntity;
import com.sino.operation.commons.response.CenterResponseEnum;
import com.sino.operation.dto.inner.LoginDto;
import com.sino.operation.entity.SysDict;
import com.sino.operation.entity.SysTeller;
import com.sino.operation.mapper.SysDictMapper;
import com.sino.operation.service.impl.SysTellerServiceImpl;
import com.sino.operation.util.CopyUtil;
import com.sino.operation.util.DateUtil;
import com.sino.operation.util.ServletInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Title: LoginService
 * @Description: 登录退出服务
 * @Author dengls
 * @date 2021/10/9 15:12
 */
@Slf4j
@Service
public class LoginService {

    @Autowired
    private SysTellerServiceImpl sysTellerService;
    @Autowired
    private ServletInfoUtil servletInfoUtil;
    @Autowired
    private RedisTaskUserService redisTaskUserService;
    @Autowired(required = false)
    private SysDictMapper sysDictMapper;

    public CenterResponseEntity
    login(SysTeller userInfo) {
        log.info("集中作业用户登录开始-login，参数:" + userInfo);
        //获取用户信息
        SysTeller sysTeller = getSysTeller(userInfo.getTellerCode());
        //校验密码
        if (userInfo.getTellerPassword().equals(sysTeller.getTellerPassword())) {
            if (TellerState.TellerState1.equals(sysTeller.getTellerState())) {
                throw new SinoException(CenterResponseEnum.USER_LOGGED_IN);
            }
            //检验是否需要强制修改密码或提醒修改密码
            String updateFlag = PasswordNeedUpdateFlag.flag_0.getValue();
            Long aLong = DateUtil.StringToLong(sysTeller.getTellerDate());
            Long nowtime = System.currentTimeMillis();
            if (nowtime - aLong > 1296000000L && nowtime - aLong < 2592000000L) {
                updateFlag = PasswordNeedUpdateFlag.flag_1.getValue();
            } else if (nowtime - aLong > 2592000000L) {
                updateFlag = PasswordNeedUpdateFlag.flag_2.getValue();
            }
            boolean isInitPassword = false;
            //检验是否初始密码
            if(userInfo.getTellerPassword().equals("123456")){
                isInitPassword = true;
            }
            //修改用户状态为签到
            sysTeller.setTellerState(TellerState.TellerState1.getValue());
            sysTellerService.saveOrUpdate(sysTeller);
            //用员工工号生成token
            String token = servletInfoUtil.setServletInfo(sysTeller.getTellerCode());
            //返回信息
            LoginDto loginDto = CopyUtil.copy(sysTeller, LoginDto.class);
            loginDto.setToken(token);
            loginDto.setUpdateFlag(updateFlag);
            loginDto.setIsInitPassword(isInitPassword);
            //查询岗位名称
            QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("distinct describe")
                    .eq("dict_value",sysTeller.getTellerPost())
                    .eq("type","岗位");
            SysDict sysDict = sysDictMapper.selectOne(queryWrapper);
            if (ObjectUtil.isNotNull(sysDict)){
                loginDto.setTellerPostName(sysDict.getDescribe());
            }
            //查询中心名称
            QueryWrapper<SysDict> sysDictQueryWrapper = new QueryWrapper<>();
            sysDictQueryWrapper.eq("dict_value",sysTeller.getCenterNo()==null?"":sysTeller.getCenterNo());
            sysDictQueryWrapper.eq("type","集中作业中心");
            SysDict sysDictCenter = sysDictMapper.selectOne(sysDictQueryWrapper);
            if (ObjectUtil.isNotNull(sysDictCenter)){
                loginDto.setCenterNoName(sysDictCenter.getDescribe());
            }
            log.info("集中作业用户" + sysTeller.getTellerCode() + "登录结束-login,token:" + token);
            return CenterResponseEntity.build(LoginDto.class).setData(loginDto);
        } else {
            throw new SinoException(CenterResponseEnum.ERROR_PASSWORD);
        }
    }

    public CenterResponseEntity loginOut() {
        String tellCode = servletInfoUtil.getServletInfo();
        if (tellCode == null) {
            throw new SinoException(CenterResponseEnum.ERROR_TOKEN);
        }
        log.info("集中作业用户" + tellCode + "退出开始-loginOut");
        //获取用户信息
        SysTeller sysTeller = getSysTeller(tellCode);
        //判断是否已经退出
        if (sysTeller.getTellerState().equals(TellerState.TellerState2.getValue())) {
            return CenterResponseEntity.build(Boolean.class).setData(false).setMsg("退出失败,柜员已经退出");
        }
        //判断能否退出
        if ((sysTeller.getWorkState() != null && sysTeller.getWorkState().equals(TellerWorkState.TellerWorkState1.getValue()))) {
            return CenterResponseEntity.build(Boolean.class).setData(false).setMsg("退出失败，柜员身上存在任务，请处理后再退出");
        }
        //修改用户状态为签退
        sysTeller.setTellerState(TellerState.TellerState2.getValue());
        sysTellerService.saveOrUpdate(sysTeller);
        //移除redis里的用户信息
        redisTaskUserService.removeUserData(sysTeller.getTellerPost(), tellCode);
        log.info("集中作业用户" + tellCode + "退出结束-loginOut");
        return CenterResponseEntity.build(Boolean.class).setData(true).setMsg("退出成功");
    }

    /**
     * 通过柜员号查询柜员信息
     *
     * @param tellerCode
     * @return
     */
    private SysTeller getSysTeller(String tellerCode) {
        QueryWrapper<SysTeller> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TELLER_CODE", tellerCode);
        return sysTellerService.getOne(queryWrapper);
    }
}
